<!--
  ③ 优化消息的临时缓存策略，发送消息时，只清理被发送消息的 tab，不会强制切回到 text 输入
  ④ 支持发送【视频】消息时，支持新建视频
-->
<template>
  <a-tabs type="card" v-model:activeKey="propObjData.type" @change="handleTabChange" class="mp-reply-tabs">
    <!-- 类型 1：文本 -->

    <a-tab-pane :key="ResponseMessageType.TEXT" tab="文本">
      <Input.TextArea placeholder="请输入内容" v-model:value="propObjData.content" :autoSize="{ minRows: 4, maxRows: 8 }" allowClear />
    </a-tab-pane>

    <!-- 类型 2：图片 -->
    <a-tab-pane :key="ResponseMessageType.IMAGE" tab="图片">
      <!-- 情况一：已经选择好素材、或者上传好图片 -->
      <div class="select-item" v-if="propObjData.url">
        <img :src="propObjData.url" />
        <p class="item-name" :on-focus="propObjData.name">{{ propObjData.name }}</p>
        <a-row class="ope-row">
          <a-button type="danger" preIcon="ant-design:delete-outlined" @click="deleteObj" />
        </a-row>
      </div>
      <!-- 情况二：未做完上述操作 -->
      <div v-else>
        <a-row style="text-align: center">
          <!-- 选择素材 -->
          <a-col :span="12" class="col-select">
            <a-button type="success" @click="openMaterial"> 素材库选择 </a-button>
            <WxMaterialSelect v-model:objData="propObjData" @select-material="selectMaterial" @register="registerModal" />
          </a-col>
          <!-- 文件上传 -->
          <a-col :span="12" class="col-add">
            <JUpload v-model:value="data.fileList" fileType="image">上传图片</JUpload>
            <!-- <div slot="tip" class="el-upload__tip">支持 bmp/png/jpeg/jpg/gif 格式，大小不超过 2M</div> -->
          </a-col>
        </a-row>
      </div>
    </a-tab-pane>

    <!-- 类型 3：语音 -->
    <!-- <a-tab-pane :key="ResponseMessageType.VOICE" tab="语音">
      <div class="select-item2" v-if="propObjData.url">
        <p class="item-name">{{ propObjData.name }}</p>
        <div class="item-infos">
          <wx-voice-player :url="propObjData.url" />
        </div>
        <a-row class="ope-row">
          <a-button type="danger" circle @click="deleteObj"></a-button>
        </a-row>
      </div>
      <div v-else>
        <a-row style="text-align: center">
          <a-col :span="12" class="col-select">
            <a-button type="success" @click="openMaterial"> 素材库选择</a-button>
          </a-col>
          <a-col :span="12" class="col-add">
            <JUpload v-model:value="propObjData.fileList" fileType="image">上传图片</JUpload>
          </a-col>
        </a-row>
      </div>
    </a-tab-pane> -->

    <!-- 类型 4：视频 -->
    <!-- <a-tab-pane :key="ResponseMessageType.VIDEO" tab="视频">
      <a-row style="text-align: center">
        <a-col :span="24" class="col-select">
          <a-button type="success" @click="openMaterial"> 素材库选择</a-button>
          <WxMaterialSelect :objData="propObjData" @selectMaterial="selectMaterial" @register="registerModal"/>
        </a-col>
      </a-row>
    </a-tab-pane> -->

    <!-- 类型 5：图文 -->
    <!-- <a-tab-pane :key="ResponseMessageType.NEWS" tab="图文">
      <a-row style="text-align: center">
        <a-col :span="24" class="col-select">
          <a-button type="success" @click="openMaterial"> 素材库选择</a-button>
        </a-col>
      </a-row>
    </a-tab-pane> -->
  </a-tabs>
</template>

<script lang="ts" setup>
  import { watch, computed, unref, useAttrs, reactive } from "vue"
  import JUpload from "/@/components/Form/src/jeecg/components/JUpload/JUpload.vue"
  import WxNews from "../WxNews/index.vue"
  import WxVoicePlayer from "../WxVoicePlayer/index.vue"
  import WxVideoPlayer from "../WxVideoPlayer/index.vue"
  import WxMaterialSelect from "../WxMaterialSelect/index.vue"
  import { Tag, Input } from "ant-design-vue"
  import { useMessage } from "/@/hooks/web/useMessage"
  import { ImagePreview } from "/@/components/Preview/index"
  import { ResponseMessageType } from "../../mpAutoReply/model"
  import { useModal } from "/@/components/Modal"
  const [registerModal, { openModal }] = useModal()

  const emit = defineEmits(["register", "update:objData"])
  // import { getAccessToken } from '@/utils/auth/'
  const props = defineProps({
    objData: {
      // 消息对象。
      type: Object, // 设置为 Object 的原因，方便属性的传递
      required: true,
    },
    newsType: {
      // 图文类型：1、已发布图文；2、草稿箱图文
      type: String,
      default: "1",
    },
  })

  const propObjData = computed({
    get: () => props.objData || {},
    set: (val) => {
      // for(let key in val) {
      //   props.objData[key] = val[key]
      // }
      selectMaterial(val)
      emit("update:objData", val)
    },
  })

  const data = reactive<any>({
    tempPlayerObj: {
      type: "2",
    },

    tempObj: new Map().set(
      // 临时缓存，切换消息类型的 tab 的时候，可以保存对应的数据；
      props.objData.type, // 消息类型
      Object.assign({}, props.objData)
    ), // 消息内容

    // ========== 素材选择的弹窗，是否可见 ==========
    dialogNewsVisible: false, // 图文
    dialogImageVisible: false, // 图片
    dialogVoiceVisible: false, // 语音
    dialogVideoVisible: false, // 视频
    dialogThumbVisible: false, // 缩略图

    // ========== 文件上传（图片、语音、视频） ==========
    fileList: [], // 文件列表
    uploadData: {
      accountId: undefined,
      type: props.objData.type,
      title: "",
      introduction: "",
    },
    actionUrl: "",
    headers: { Authorization: "Bearer " },
  })

  const beforeThumbImageUpload = (file) => {
    const isType =
      file.type === "image/jpeg" || file.type === "image/png" || file.type === "image/gif" || file.type === "image/bmp" || file.type === "image/jpg"
    if (!isType) {
      // this.$message.error('上传图片格式不对!');
      return false
    }
    const isLt = file.size / 1024 / 1024 < 2
    if (!isLt) {
      // this.$message.error('上传图片大小不能超过 2M!');
      return false
    }
    // this.uploadData.accountId = this.objData.accountId;
    return true
  }
  const beforeVoiceUpload = (file) => {
    // 校验格式
    const isType =
      file.type === "audio/mp3" || file.type === "audio/mpeg" || file.type === "audio/wma" || file.type === "audio/wav" || file.type === "audio/amr"
    if (!isType) {
      // this.$message.error('上传语音格式不对!' + file.type);
      return false
    }
    // 校验大小
    const isLt = file.size / 1024 / 1024 < 2
    if (!isLt) {
      // this.$message.error('上传语音大小不能超过 2M!');
      return false
    }
    // this.uploadData.accountId = this.objData.accountId;
    return true
  }
  const beforeImageUpload = (file) => {
    // 校验格式
    const isType =
      file.type === "image/jpeg" || file.type === "image/png" || file.type === "image/gif" || file.type === "image/bmp" || file.type === "image/jpg"
    if (!isType) {
      // this.$message.error('上传图片格式不对!');
      return false
    }
    // 校验大小
    const isLt = file.size / 1024 / 1024 < 2
    if (!isLt) {
      // this.$message.error('上传图片大小不能超过 2M!');
      return false
    }
    // this.uploadData.accountId = this.objData.accountId;
    return true
  }
  const beforeVideoUpload = (file) => {
    // 校验格式
    const isType = file.type === "video/mp4"
    if (!isType) {
      // this.$message.error('上传视频格式不对!');
      return false
    }
    // 校验大小
    const isLt = file.size / 1024 / 1024 < 10
    if (!isLt) {
      // this.$message.error('上传视频大小不能超过 10M!');
      return false
    }
    // this.uploadData.accountId = this.objData.accountId;
    return true
  }
  const handleUploadSuccess = (response, file, fileList) => {
    if (response.code !== 0) {
      // this.$message.error('上传出错：' + response.msg)
      return false
    }

    // 清空上传时的各种数据
    data.fileList = []
    data.uploadData.title = ""
    data.uploadData.introduction = ""

    // 上传好的文件，本质是个素材，所以可以进行选中
    let item = response.data
    selectMaterial(item)
  }
  /**
   * 切换消息类型的 tab
   *
   * @param tab tab
   */
  const handleTabChange = (tab) => {
    console.log("current tab: ", tab)

    props.objData.type = tab
    // 设置后续文件上传的文件类型
    data.uploadData.type = props.objData.type
    if (data.uploadData.type === "music") {
      // 【音乐】上传的是缩略图
      data.uploadData.type = "thumb"
    }

    // 从 tempObj 临时缓存中，获取对应的数据，并设置回 objData
    let tempObjItem = data.tempObj.get(props.objData.type)
    console.log("tempObjItem", tempObjItem)

    if (tempObjItem) {
      // props.objData.content = tempObjItem.content ? tempObjItem.content : null
      // props.objData.mediaId = tempObjItem.mediaId ? tempObjItem.mediaId : null
      // props.objData.url = tempObjItem.url ? tempObjItem.url : null
      // props.objData.name = tempObjItem.url ? tempObjItem.name : null
      // props.objData.title = tempObjItem.title ? tempObjItem.title : null
      // props.objData.description = tempObjItem.description ? tempObjItem.description : null
      return
    }
    // 如果获取不到，需要把 objData 复原
    // 必须使用 $set 赋值，不然 input 无法输入内容
    // this.$set(this.objData, 'content', '');
    // this.$delete(this.objData, 'mediaId');
    // this.$delete(this.objData, 'url');
    // this.$set(this.objData, 'title', '');
    // this.$set(this.objData, 'description', '');
  }
  /**
   * 选择素材，将设置设置到 objData 变量
   *
   * @param item 素材
   */
  const selectMaterial = (item) => {
    // 选择好素材，所以隐藏弹窗
    closeMaterial()

    // 创建 tempObjItem 对象，并设置对应的值
    let tempObjItem: any = {}
    tempObjItem.type = props.objData.type
    if (props.objData.type === ResponseMessageType.NEWS) {
      tempObjItem.articles = item.content.newsItem
      props.objData.articles = item.content.newsItem
    } else if (props.objData.type === ResponseMessageType.MUSIC) {
      // 音乐需要特殊处理，因为选择的是图片的缩略图
      tempObjItem.thumbMediaId = item.mediaId
      props.objData.thumbMediaId = item.mediaId
      tempObjItem.thumbMediaUrl = item.url
      props.objData.thumbMediaUrl = item.url
      // title、introduction、musicUrl、hqMusicUrl：从 objData 到 tempObjItem，避免上传素材后，被覆盖掉
      tempObjItem.title = props.objData.title || ""
      tempObjItem.introduction = props.objData.introduction || ""
      tempObjItem.musicUrl = props.objData.musicUrl || ""
      tempObjItem.hqMusicUrl = props.objData.hqMusicUrl || ""
    } else if (props.objData.type === ResponseMessageType.IMAGE || props.objData.type === ResponseMessageType.VOICE) {
      tempObjItem.mediaId = item.mediaId
      props.objData.mediaId = item.mediaId
      tempObjItem.url = item.url
      props.objData.url = item.url
      tempObjItem.name = item.name
      props.objData.name = item.name
    } else if (props.objData.type === ResponseMessageType.VIDEO) {
      tempObjItem.mediaId = item.mediaId
      props.objData.mediaId = item.mediaId
      tempObjItem.url = item.url
      props.objData.url = item.url
      tempObjItem.name = item.name
      props.objData.name = item.name
      // title、introduction：从 item 到 tempObjItem，因为素材里有 title、introduction
      if (item.title) {
        props.objData.title = item.title || ""
        tempObjItem.title = item.title || ""
      }
      if (item.introduction) {
        props.objData.description = item.introduction || "" // 消息使用的是 description，素材使用的是 introduction，所以转换下
        tempObjItem.description = item.introduction || ""
      }
    } else if (props.objData.type === ResponseMessageType.TEXT) {
      props.objData.content = item.content || ""
    }
    // 最终设置到临时缓存
    data.tempObj.set(props.objData.type, tempObjItem)
  }
  const openMaterial = () => {
    // if (props.objData.type === 'news') {
    //   data.dialogNewsVisible = true
    // } else if (props.objData.type === 'image') {
    //   data.dialogImageVisible = true
    // } else if (props.objData.type === 'voice') {
    //   data.dialogVoiceVisible = true
    // } else if (props.objData.type === 'video') {
    //   data.dialogVideoVisible = true
    // } else if (props.objData.type === 'music') {
    //   data.dialogThumbVisible = true
    // }

    openModal(true, {
      type: props.objData.type,
    })
  }
  const closeMaterial = () => {
    data.dialogNewsVisible = false
    data.dialogImageVisible = false
    data.dialogVoiceVisible = false
    data.dialogVideoVisible = false
    data.dialogThumbVisible = false
  }
  const deleteObj = () => {
    if (props.objData.type === ResponseMessageType.NEWS) {
      delete props.objData.articles
    } else if (props.objData.type === ResponseMessageType.IMAGE) {
      props.objData.mediaId = null
      props.objData.name = null
      delete props.objData.url
    } else if (props.objData.type === ResponseMessageType.VOICE) {
      props.objData.mediaId = null
      delete props.objData.url
      props.objData.name = null
    } else if (props.objData.type === ResponseMessageType.VIDEO) {
      props.objData.mediaId = null
      props.objData.name = null
      props.objData.title = null
      props.objData.description = null
      delete props.objData.url
    } else if (props.objData.type === ResponseMessageType.MUSIC) {
      props.objData.thumbMediaId = null
      props.objData.thumbMediaUrl = null
      props.objData.title = null
      props.objData.description = null
      props.objData.musicUrl = null
      props.objData.hqMusicUrl = null
      props.objData.description = null
    } else if (props.objData.type === ResponseMessageType.TEXT) {
      props.objData.content = null
    }
    data.tempObj.set(props.objData.type, Object.assign({}, props.objData))
  }

  /**
   * 输入时，缓存每次 objData 到 tempObj 中
   *
   * why？不确定为什么 v-model="objData.content" 不能自动缓存，所以通过这样的方式
   */
  const inputContent = (str) => {
    // 覆盖缓存
    // this.tempObj.set(this.objData.type, Object.assign({}, this.objData));
  }
</script>

<style lang="less" scoped>
  .mp-reply-tabs {
    padding: 10px;
    background: #fafafa !important;

    .ant-tabs-tabpane {
      width: 100%;
      background: #fff !important;
    }
  }

  .card-container > .ant-tabs-card > .ant-tabs-nav::before {
    display: none;
  }

  .public-account-management {
    .el-input {
      width: 70%;
      margin-right: 2%;
    }
  }

  .pagination {
    text-align: right;
    margin-right: 25px;
  }

  .select-item {
    width: 180px;
    padding: 10px;
    margin: 0 auto 10px auto;
    border: 1px solid #eaeaea;
  }

  .select-item2 {
    padding: 10px;
    margin: 0 auto 10px auto;
    border: 1px solid #eaeaea;
  }

  .ope-row {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
  }

  .item-name {
    font-size: 12px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    text-align: center;
  }

  .el-form-item__content {
    line-height: unset !important;
  }

  .col-select {
    border: 1px solid rgb(234, 234, 234);
    padding: 50px 0px;
    height: 160px;
    width: 49.5%;
  }

  .col-select2 {
    border: 1px solid rgb(234, 234, 234);
    padding: 50px 0px;
    height: 160px;
  }

  .col-add {
    border: 1px solid rgb(234, 234, 234);
    padding: 50px 0px;
    height: 160px;
    display: flex;
    justify-content: center;
    flex-direction: column;
    width: 49.5%;
  }

  .avatar-uploader-icon {
    border: 1px solid #d9d9d9;
    font-size: 28px;
    color: #8c939d;
    width: 100px !important;
    height: 100px !important;
    line-height: 100px !important;
    text-align: center;
  }

  .material-img {
    width: 100%;
  }

  .thumb-div {
    display: inline-block;
    text-align: center;
  }

  .item-infos {
    width: 30%;
    margin: auto;
  }
</style>
